package comp

import (
	"encoding/json"
	"fmt"
	"fucker/frame/config"
	"fucker/frame/db"
	"fucker/frame/factory"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"io/ioutil"
	"log"
)

func StartFromConfigFile(file string) {

	config := config.ParseJsonConfig(file)

	log.Println(config)

	app := GetApp(config)

	comp := GetComp(config)

	app.SetContent(comp)
	app.ShowAndRun()
}

func AppConfig(appConfig string, UIConfig string) {
	app := getApp(appConfig)

	appInit(app)

	StartFromConfigFile(UIConfig)
}

func appInit(appConfig *config.App) {
	if appConfig.DB != nil && appConfig.DB.Enable {
		db.InitDb(appConfig.DB)
	}
}
func getApp(path string) *config.App {
	file, err := ioutil.ReadFile(path)
	if err != nil {
		panic("config file not found path:" + path)
	}

	app := &config.App{}
	err = json.Unmarshal(file, app)

	if err != nil {
		panic("config file init fail " + err.Error())
	}

	return app
}

func GetComp(c *config.UI) fyne.CanvasObject {
	child := c.Child

	comp := DoGetComp2(child[0])
	return comp
}

func DoGetComp(node *config.Child) fyne.CanvasObject {
	root := factroy.Create(node)

	if node.Type == "layout" {
		if node.Key == "hscroll" || node.Key == "vscroll" {

		}
	}

	container, err := root.(*fyne.Container)

	if !err {
		w, e := root.(fyne.CanvasObject)

		if !e {
			panic(e)
		}

		return w
	}
	for _, subNode := range node.Child {
		childTree := DoGetComp2(subNode)
		container.Add(childTree)
	}

	return root.(fyne.CanvasObject)
}
func DoGetComp2(node *config.Child) fyne.CanvasObject {
	var temp []fyne.CanvasObject
	if node.Child != nil && len(node.Child) > 0 {

		for _, c := range node.Child {
			comp2 := DoGetComp2(c)
			temp = append(temp, comp2)
		}

		fmt.Println(temp)
	}

	var root interface{}

	if createTimeSub(node) {
		root = factroy.CreateWithChild(node, temp)
	} else {
		root = factroy.Create(node)
	}

	rootNode, succ := root.(*fyne.Container)

	if succ {
		if len(temp) > 0 {
			for _, sub := range temp {
				rootNode.Add(sub)
			}
		}

		return rootNode
	}

	return root.(fyne.CanvasObject)
}

func createTimeSub(node *config.Child) bool {
	if node.Key == "hscroll" || node.Key == "vscroll" {
		return true
	}

	return false
}
func GetApp(c *config.UI) fyne.Window {
	a := app.NewWithID(c.AppId)
	window := a.NewWindow(c.Title)

	window.Resize(fyne.NewSize(c.Weight, c.Height))

	return window
}
